// 生产环境作为默认原始地址
// 初始化规则
chrome.runtime.onInstalled.addListener(() => {
  // 加载保存的环境或使用默认
  chrome.storage.local.get('currentEnv', (result) => {
    const targetUrl = result.currentEnv.target?.url || result.currentEnv.targets[0]?.url || result.currentEnv.url;
    console.log(7788, result.currentEnv);
    updateRules(result.currentEnv.url, targetUrl).then(success => success ? injectToCurrentTab(result.currentEnv) : false)
    return true; // 保持消息通道开放
  });
});

// 监听环境切换消息  点击按钮切换的时候
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'switchEnv') {
    let env = message.env
    const targetUrl = env.target?.url || env.targets[0]?.url || env.url;
    updateRules(env.url, targetUrl).then(success => success ? injectToCurrentTab(env) : false)
    sendResponse({ success: true });// 
    return true; // 保持消息通道开放
  }
  // 移除选择的环境
  if (message.action === 'removeEnv') {
    console.log(7788);

    removeRules()
    sendResponse({ success: true });// 
    return true; // 保持消息通道开放
  }
});
// 更新网络请求规则
function updateRules(origin, target) {
  return new Promise((resolve, reject) => {
    // 清除现有动态规则
    chrome.declarativeNetRequest.getDynamicRules((rules) => {
      const ruleIds = rules.map(rule => rule.id);
      chrome.declarativeNetRequest.updateDynamicRules({
        removeRuleIds: ruleIds,
        addRules: createRules(origin, target),

      }, () => {
        if (chrome.runtime.lastError) {
          console.error("规则更新失败:", chrome.runtime.lastError);
          resolve(false);
        } else {
          console.log("规则更新成功:", 666);
          resolve(true);
        }
      });
    });
  });

}

// 创建重定向规则
function createRules(origin, target) {
  // 只在目标不是原始地址时创建规则
  if (origin === target) {
    return [];
  }

  return [
    {
      id: 1,
      priority: 1,
      action: {
        type: 'redirect',
        redirect: {
          regexSubstitution: target + '\\1'
        }
      },
      condition: {
        regexFilter: `${origin}(.*)`,
        resourceTypes: ["main_frame",    // 主页面
          "sub_frame",     // 子框架
          "xmlhttprequest", // AJAX请求（包括fetch的底层实现）
          "script",        // 脚本文件
          "stylesheet",    // 样式表
          "image",         // 图片资源
          "font",          // 字体文件
          "media",         // 媒体文件
          "websocket"      // WebSocket连接
        ]
      }
    }
  ];
}
// 监听当前标签页并注入脚本
function injectToCurrentTab(data) {
  return new Promise((resolve) => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs.length > 0) {
        injectEnvScript(tabs[0].id, data).then(resolve);
        // resolve(true);
      } else {
        resolve(false);
      }
    });
  });
}
// 注入脚本
function injectEnvScript(tabId, data) {
  // return
  return new Promise((resolve) => {
    chrome.scripting.executeScript({
      target: { tabId: tabId, allFrames: true },
      world: "MAIN",
      injectImmediately: true,
      args: [data],// 传入参数
      func: (data) => {
        try {
          if (CONFIG) {
            console.log('CONFIG', CONFIG);
            let url = data.target?.url || data.targets[0]?.url || data.url
            let env = "";
            if (url.includes("-dev.")) {
              env = "-dev";
            } else if (url.includes("-qa.")) {
              env = "-qa";
            }
            let utilsUrl = `https://utils${env}.newtypegames.com`;
            let SSOLogoutUrl = `https://sso-api${env}.taiyouxi.cn/server/oauth`;
            let SSOUrl = `https://sso${env}.taiyouxi.cn/login`;

            CONFIG.baseUrl = url
            CONFIG.utilsUrl = utilsUrl
            CONFIG.SSOLogoutUrl = SSOLogoutUrl
            CONFIG.SSOUrl = SSOUrl
            console.log('CONFIGobjobj', CONFIG);
          } else {
            console.log('还不存在！！！');
          }
        } catch (error) {
          console.log('失败了可能不存在');
          let CONFIG = {}
          let url = data.target?.url || data.targets[0]?.url || data.url
          let env = "";
          if (url.includes("-dev.")) {
            env = "-dev";
          } else if (url.includes("-qa.")) {
            env = "-qa";
          }
          let utilsUrl = `https://utils${env}.newtypegames.com`;
          let SSOLogoutUrl = `https://sso-api${env}.taiyouxi.cn/server/oauth`;
          let SSOUrl = `https://sso${env}.taiyouxi.cn/login`;

          let obj = {
            baseUrl: url,
            utilsUrl,
            SSOLogoutUrl,
            SSOUrl,
          }

          CONFIG = obj
          window.CONFIG = CONFIG

        }
        console.log("环境切换成功，当前baseUrl:");
        return true;
      }
    }, (results) => {
      if (chrome.runtime.lastError) {
        console.error("脚本注入失败:", chrome.runtime.lastError);
        resolve(false);
      } else {
        resolve(true);
      }
    })
  })
}
function removeRules() {
  return new Promise((resolve) => {
    chrome.declarativeNetRequest.getDynamicRules((rules) => {
      const ruleIds = rules.map(rule => rule.id);
      console.log('removeRules--ruleIds:', ruleIds);

      // 移除规则
      chrome.declarativeNetRequest.updateDynamicRules({
        removeRuleIds: ruleIds
      }, () => {
        if (chrome.runtime.lastError) {
          console.error("清除规则失败:", chrome.runtime.lastError);
          resolve(false);
        } else {
          console.log("指定动态规则已清除--removeRules");
          resolve(true);
        }
      })
    })

  })
}

// 监听页面加载完成事件，自动注入环境配置
chrome.webNavigation.onDOMContentLoaded.addListener((details) => {
  if (details.url.includes("localhost")) {
    chrome.storage.local.get('currentEnv', (result) => {
      console.log(details, '---');

      if (result.currentEnv) {
        const targetUrl = result.currentEnv.target?.url || result.currentEnv.targets[0]?.url || result.currentEnv.url;
        updateRules(result.currentEnv.url, targetUrl).then(success => success ? injectToCurrentTab(result.currentEnv) : false)
      }
    });
  }
});

// 监听页面导航开始前的事件（最早能注入的时机之一）
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
  // 只处理目标网站（可根据需要限制域名）


  if (details.url.includes("localhost")) {
    chrome.storage.local.get('currentEnv', (result) => {
      if (result.currentEnv) {
        const targetUrl = result.currentEnv.target?.url || result.currentEnv.targets[0]?.url || result.currentEnv.url;
        setTimeout(() => {
          updateRules(result.currentEnv.url, targetUrl).then(success => success ? injectToCurrentTab(result.currentEnv) : false)
        }, 500);
      }
    });
  }
}, { urls: ["<all_urls>"] }); // 监听所有 URL 的导航